package com.buptlogistics.creditinvestigation.fragment;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.LogInCallback;
import com.buptlogistics.creditinvestigation.R;
import com.buptlogistics.creditinvestigation.activity.MainActivity;
import com.buptlogistics.creditinvestigation.app.AppData;
import com.buptlogistics.creditinvestigation.app.BaseFragment;
import com.buptlogistics.creditinvestigation.entity.User;


/**
 * LoginActivity
 * <p/>
 * renweiwei renweiwei 2014-7-15 上午10:56:38
 *
 * @version 1.0.0
 */
public class LoginFragment extends BaseFragment {

    private EditText et_accounts;
    private EditText et_password;
    private Button bt_login;
    private LinearLayout bgLayout;

    public static String mAppid;

    private String username, key;
    private View view;
    // 进度条
    //TODO  progress dialog show
    private final ProgressDialog progressDialog = null;

    /** 登出操作对应的listener */
    // private LogOutRequestListener mLogoutListener = new
    // LogOutRequestListener();

    /**
     * 创建一个新的实例 LoginActivity.
     */
    public LoginFragment() {

    }

    /*
     * (non-Javadoc)
     *
     * @see
     * com.hmammon.campuscalendar.app.BaseActivity#onCreate(android.os.Bundle)
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_login, container, false);
        AppData.getInstance(getActivity());
        // LeanCloudUtil.getInstance(getActivity());
        // LeanCloud
        // 如果使用美国节点，请加上这行代码 AVOSCloud.useAVCloudUS();
        initViews();
        initEvents();
        return view;
    }

    /*
     * (non-Javadoc)
     *
     * @see com.hmammon.campuscalendar.app.BaseActivity#initViews()
     */
    protected void initViews() {
        et_accounts = (EditText) view.findViewById(R.id.accounts);
        et_password = (EditText) view.findViewById(R.id.password);
        bt_login = (Button) view.findViewById(R.id.login);
        // bt_login.setBackgroundResource(R.drawable.login_button_style);
        bgLayout = (LinearLayout) view.findViewById(R.id.login_input);
    }

    /*
     * (non-Javadoc)
     *
     * @see com.hmammon.campuscalendar.app.BaseActivity#initEvents()
     */
    protected void initEvents() {
        bt_login.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (TextUtils.isEmpty(et_accounts.getText())) {
                    Toast.makeText(LoginFragment.this.getActivity(), "用户名不能为空",
                            Toast.LENGTH_SHORT).show();
                    return;
                } else if (TextUtils.isEmpty(et_password.getText())) {
                    Toast.makeText(LoginFragment.this.getActivity(), "密码不能为空",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                username = et_accounts.getText().toString().trim();
                key = et_password.getText().toString().trim();

                //TODO
                //IcyBeeUtil.login(username, key, LoginFragment.this.getActivity());
                login(username,et_password.getText().toString(),LoginFragment.this.getActivity());

            }
        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

    }

    /**
     * （非 Javadoc）
     * <p>
     * Title: onResume
     * </p>
     * <p>
     * Description:
     * </p>
     *
     * @see android.support.v4.app.Fragment#onResume()
     */
    @Override
    public void onResume() {
        // LogUtil.i("onResume", "loginFragment onResume");
        // if (AVUser.getCurrentUser() != null) {
        // Log.i("is login", "has logined,finish LoginRegistActivity");
        // getActivity().finish();
        // } else {
        // Log.i("is login", "not login");
        // }
        super.onResume();
    }
    /**
     //     * <p>
     //     * Title: login
     //     * </p>
     //     * <p>
     //     * Description:login 对象数组法 匿名内部类返回值
     //     * </p>
     //     *
     //     * @param userName
     //     * @param password
     //     */
   public static AVUser login(String userName, final String password,
                              final Context nContext) {
        AppData.getInstance(nContext);
        final AVUser avuser[] = new AVUser[1];
        AVUser.logInInBackground(userName, password,
                new LogInCallback<AVUser>() {
                    @Override
                    public void done(AVUser user, AVException e) {
                        if (e == null) {
                            if (user != null) {
                                avuser[0] = user;
                                Log.i("success", user.toJSONObject().toString());
                                Log.i("LeanCloudUtils", AVUser.getCurrentUser()
                                        .getUsername());
                                Log.i("current user", AVUser.getCurrentUser()
                                        .toJSONObject().toString());
                                User user_new=new User(AVUser.getCurrentUser()
                                        .getUsername(),password,AVUser.getCurrentUser().getString("phone"),AVUser.getCurrentUser().getString("company"),AVUser.getCurrentUser().getString("company_code"));
                                AppData.getInstance(nContext).saveUserInfo(user_new.toString());
                   //             AppData.getInstance(nContext).setUserPassword(password);
                                AppData.getInstance(nContext).setLogin(true);
                                nContext.startActivity(new Intent(nContext, MainActivity.class));
                            } else {
                                Log.e("login failed", "未查询到用户");
                                Toast.makeText(nContext, "用户名密码不匹配",
                                        Toast.LENGTH_SHORT).show();
                            }

                        } else {
                            Log.e("failed", e.toString());
                        }

                    }
                });
        return avuser[0];
    }

}
